package cn.chrisx.drad.audiencenetwork;

import android.content.Context;

import com.facebook.ads.RewardData;
import com.facebook.ads.RewardedVideoAd;
import com.facebook.ads.RewardedVideoAdListener;

/**
 * @author Jzfox <jz_boy@163.com>
 * @version 1.0
 * @date 2018/9/26 16:02
 * @description
 * @copyright ©2018 www.jzfox.net All rights reserved.
 */
public class RewardVideoImpl extends BaseAd implements RewardedVideoAdListener {

    private RewardedVideoAd rewardedVideoAd;

    private boolean serverReward;

    @Override
    public boolean loadAd(Context context) {
        if (rewardedVideoAd == null) {
            // Instantiate a RewardedVideoAd object.
            // NOTE: the placement ID will eventually identify this as your App, you can ignore it for
            // now, while you are testing and replace it later when you have signed up.
            // While you are using this temporary code you will only get test ads and if you release
            // your code like this to the Google Play your users will not receive ads (you will get a no fill error).

            rewardedVideoAd = new RewardedVideoAd(context, drAdConfig.getAdUnitId());
            rewardedVideoAd.setAdListener(this);

            //Set the rewarded ad data
            if (drAdConfig instanceof AudienceNetworkAdConfig) {
                RewardData rd = ((AudienceNetworkAdConfig) drAdConfig).getRewardData();

                if (rd != null) {
                    serverReward = true;
                    rewardedVideoAd.setRewardData(rd);
                } else {
                    serverReward = false;
                }
            }


            // Alternateively, you can set the RewardData after the loadAd method
            // rewardedVideoAd.setRewardData(new RewardData("YOUR_USER_ID", "YOUR_REWARD"));
        }

        rewardedVideoAd.loadAd();
        return true;
    }

    @Override
    public void onDestroy(Context context) {
        if (rewardedVideoAd != null) {
            rewardedVideoAd.destroy();
        }
    }

    @Override
    public boolean show() {
        return isValid() && rewardedVideoAd.show();
    }

    @Override
    public boolean isValid() {
        return rewardedVideoAd != null && rewardedVideoAd.isAdLoaded();
    }

    @Override
    public void onRewardedVideoCompleted() {
        // Rewarded Video View Complete - the video has been played to the end.
        // You can use this event to initialize your reward
        if (!serverReward) {
            onReward(true, null);
        }

    }

    @Override
    public void onRewardedVideoClosed() {
        // The Rewarded Video ad was closed - this can occur during the video
        // by closing the app, or closing the end card.
        onAdDismiss();
    }
}
